<template>
	<view class="l-fc l-fw" style="margin: 0 -6px;">
		<block v-if="list&&list.length>0">
			<view v-for="(item, index) in list" :key="index" class="c-bg-f o-mlr-s o-mt l-box"
				style="width: 140rpx;height: 140rpx;">
				<view @click="deletePicture(index)" class="o-p-s"
					style="position: absolute;top:-26rpx;right: -20rpx;z-index: 90;">
					<u-icon name="close-circle-fill" color="#dd524d" size="32"></u-icon>
				</view>
				<view class="wh100 c-of-h">
					<image class="w100" @click="$Function.PreviewImage(list,index)" mode="widthFix" :src="item"></image>
				</view>
			</view>
		</block>
		<view @click="addPicture()" v-if="list.length<num" class="c-of-h c-bg-f o-mlr-s o-mt"
			style="width: 140rpx;height: 140rpx;">
			<image class="wh100" src="/static/images/addImg.png"></image>
		</view>
	</view>
</template>

<script>
	import config from '../common/config.js'; //用于图片上传地址的拼接
	export default {
		data() {
			return {
				list: [], //图片的列表
				OList:[]
			}
		},
		props: {
			num: {
				type: Number,
				default: 9
			},
			idx: {
				type: Number,
				default: 0
			},
			imgs: {
				type: String,
				default: ''
			}
		},
		created() {
			if(this.imgs) {
				this.list = this.imgs.split(','); //图片列表的合并
				let imgUrl = []
				for(let i = 0; i < this.imgs.length; i++) {
					let url = this.$Function.intercept(this.imgs[i], 'tiwang', 1)
					imgUrl.push(url)
				}
				this.OList = this.OList.concat(imgUrl)
			}
		},
		methods: {
			addPicture() {
				uni.chooseImage({
					count: this.num, // 最多可以选择的图片张数，默认9
					sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						const tempFiles = chooseImageRes.tempFiles;
						uni.showLoading({
							title: '图片上传中...',
							mask: true
						});
						var promise = Promise.all(tempFilePaths.map((pic, i) => {
							return new Promise(async (resolve, reject) => {
								let cimg = null;
								// #ifdef APP-PLUS
								cimg = await this.compress(pic) //上传图片之前先压缩，否则上传会比压缩先执行
								// #endif
								// #ifdef MP-WEIXIN
								if(tempFiles[i].size > 512000) {
									cimg = await this.WXcompress(pic) //上传图片之前先压缩，否则上传会比压缩先执行
								}else{
									cimg = pic
								}
								// #endif
								// #ifdef H5
								cimg = pic
								// #endif
								uni.uploadFile({
									url: config.action, //仅为示例，非真实的接口地址
									header: {
										"Blade-Auth": 'bearer ' + uni.getStorageSync('token')
									},
									filePath: cimg,
									name: 'file',
									formData: {},
									success: (uploadFileRes) => {
										let data = JSON.parse(uploadFileRes.data)
										if (data.code == 401) {
											this.$Function.LinkTo('/pages/mine/sign','Rl')
											return
										}
										// console.log('data ==>', data.data.link)
										// resolve(config.image_qz+data.data.name)
										resolve(data.data.name)
									},
									fail: (err) => {
										console.log('err ==>', err)
										uni.hideLoading();
									}
								});
							})
						}))

						promise.then(res => {
							let imgUrl = []
							this.OList = this.OList.concat(res)
							for(let i = 0; i < res.length; i++) {
								imgUrl.push(config.image_qz+res[i])
							}
							this.list = this.list.concat(imgUrl)
							uni.hideLoading();
						})
					}
				});
			},
			//删除图片
			deletePicture(imgidx) {
				let list = this.list; //图片的数组
				let OList = this.OList; //图片的数组
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗',
					success: (res) => {
						if (res.confirm) {
							list.splice(imgidx, 1);
							OList.splice(imgidx, 1);
							this.list = list;
							this.OList = OList;
						} else if (res.cancel) {

						}
					}
				})
			},
			//压缩图片
			compress(img) {
				// console.log('开始压缩 ==>', img);
				return new Promise((resolve) => {
					// var localPath = plus.io.convertAbsoluteFileSystem(img);
					plus.io.resolveLocalFileSystemURL(img, (entry) => { //通过URL参数获取目录对象或文件对象
						entry.file((file) => { // 可通过entry对象操作图片 
							// console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
							if (file.size > 512000) { //   如果大于500Kb进行压缩
								plus.zip.compressImage({ // 5+ plus.zip.compressImage 了解一下，有详细的示例
										src: img, //src: 压缩原始图片的路径    
										dst: img.replace('.png', '.png').replace('.PNG',
											'.PNG').replace('.jpg', '.jpg').replace('.JPG',
											'.JPG'),
										width: '50%', //dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个2222区分一下
										height: '50%', //width,height: (String 类型 )缩放图片的宽度,高度
										quality: 70, //quality: (Number 类型 )压缩图片的质量
										overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
										// format:'jpg'   //format: (String 类型 )压缩转换后的图片格式
									},
									(event) => {
										// console.log('压缩后图片信息:' + JSON.stringify(event));// 压缩后图片信息
										// this.imageInfo=event
										let newImg = event.target;
										resolve(newImg); //返回新的图片地址，在uploadFile之前接收
									},
									(err) => {
										// console.log('Resolve file URL failed: ' + err.message);
									});
							} else { //else小于500kb跳过压缩，直接返回现有的src
								resolve(img);
							}
						});
					}, (e) => { // 返回错误信息
						uni.hideLoading();
						// console.log('Resolve file URL failed: ' + e.message);
					});
				})
			},
			// 微信压缩
			WXcompress(img) {
				return new Promise((resolve, reject) => {
					uni.compressImage({
					  src: img,
					  width: '50%',
					  height: '50%', 
					  quality: 70, //压缩质量，范围0～100，数值越小，质量越低，压缩率越高（仅对jpg有效）
					  success: res => {
						  resolve(res.tempFilePath)
						  uni.hideLoading();
					  }
					})
				})
			}
		}
	}
</script>

<style>
</style>
